import router from '@/router'
import type { RouteRecordDto, RouteRecordMetaDto } from '@/api/login/types'
import { useBasicStore } from '@/stores/basic'
import type { RouteRecordRaw } from 'vue-router'
import { ButtonMenuTypeCnEnum } from '@/const/enum'

/**
 * 导入所有在指定目录下的 tsx 组件，并将它们合并成一个对象。
 * @returns 包含所有 Vue 文件路径及其对应模块的对象。
 */
const modules = () => {
    return import.meta.glob(['@/views/*.tsx', '@/views/**/*.tsx'])
}

// const getModules = require.context('@/views', true, /\.vue|\.tsx$/)

const getBtnRoute = (btnChildren: RouteRecordMetaDto['btnChildren'], isTab: boolean) => {
    return btnChildren?.filter((btn) => btn.path && (isTab ? btn.btnPosition === ButtonMenuTypeCnEnum.标签页 : btn.btnPosition !== ButtonMenuTypeCnEnum.标签页))?.map((btn) => {
        return {
            path: btn.path,
            redirect: '',
            meta: {
                ...btn,
                hidden: true
            }
        } as RouteRecordDto
    }) ?? []
}

/**
 * 创建组件函数
 *
 * @param routers 路由数组
 */
const createComponents = (routers: RouteRecordDto[]) => {
    const childrenViews = [] as RouteRecordDto[]
    const routerViews =  routers.map((route) => {

        const btnChildren = route.meta?.btnChildren || []

        // 判断是否为tabs页面
        const hasTabsView = btnChildren.filter((btn) => btn.btnPosition === ButtonMenuTypeCnEnum.标签页).length > 0
        // console.log(route.path, hasTabsView,JSON.parse(JSON.stringify(btnChildren)), 'hasTabsView')
        
        const routeMapResult = route.path
        // 将动态路由转为detail组件
        const routeMapResultComponent = (routeMapResult || '').replace(/\/:.+/, '/detail')

        // 匹配tabs页面或指定界面
        const component = hasTabsView ? modules()['/src/views/Tabs.tsx'] : modules()[`/src/views${routeMapResultComponent}/Index.tsx`]
        
        let children = [] as RouteRecordDto[]

        if (route.children && route.children.length) {
            children = createComponents(route.children)
        }

        if (hasTabsView) { // 清洗标签页
            console.log('hasTabsView', route.path)
            const btnChildrenRecord = getBtnRoute(btnChildren, true)
            const btnViews = createComponents(btnChildrenRecord).map(btn => {
                return {
                    ...btn,
                    meta: {
                        ...btn.meta,
                        noCache: false
                    }
                }
            }) as RouteRecordDto[]
            route.redirect = btnViews[0].path
            children.push(...btnViews)
        }

        { // 按钮页面提取到外层
            const btnChildrenRecord = getBtnRoute(btnChildren, false)
            const btnViews = createComponents(btnChildrenRecord).map(btn => {
                return {
                    ...btn,
                    meta: {
                        ...btn.meta,
                        noCache: true
                    }
                }
            }) as RouteRecordDto[]
            childrenViews.push(...btnViews)
        }

        return {
            ...route,
            path: routeMapResult || `${route.path}`,
            children,
            redirect: route.redirect === 'noRedirect' ? '' : route.redirect,
            component,
        } as RouteRecordDto
    })
    return [
        ...childrenViews,
        ...routerViews
    ]
}

/**
 * 生成异步的路由
 *
 * @param routers 路由列表
 */
export function initRouter(sourceRouters: RouteRecordDto[]) {
    const routers = createComponents(sourceRouters)
    if (routers[0]?.children && routers[0].children[0]) {
        router.addRoute({
            ...routers[0].children[0],
            path: '/',
            name: '/',
        })
    }
    routers.forEach((route) => {
        router.addRoute(route)
    })
    console.log('routers', routers)
    const basicStore = useBasicStore()
    basicStore.setMenuList(routers)
}
